#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>


static int read_file_list(char * path)
{
  DIR * dir;
  struct dirent * ptr;
  char base[512];
  struct stat st;
  int ret = -1;
  char absolutely_path[512];


  if ((dir = opendir(path)) == NULL) {
    perror("open dir error...");
    exit(1);
  }

  memset(base, 0, sizeof base);
  memset(absolutely_path, 0, sizeof absolutely_path);

  while ((ptr = readdir(dir)) != NULL) {
    if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
      continue;
    else if (ptr->d_type == 8) { 		/* file */
	  //printf("file:%s/%s\n", path, ptr->d_name);
	  strcpy(absolutely_path, path);
	  strcat(absolutely_path + strlen(path), "/");
	  strcat(absolutely_path + strlen(path) + 1, ptr->d_name);
      printf("file:%s%s\n", path, ptr->d_name);
	  printf("abso:%s\n", absolutely_path);
	}
    else if (ptr->d_type == 10)	{	/* link file */
      //printf("link:%s/%s\n", path, ptr->d_name);
	}
    else if (ptr->d_type == 4) {	/* dir */
      memset(base, 0, sizeof base);
      strcpy(base, path);
      strcat(base, "/");
      strcat(base, ptr->d_name);
      read_file_list(base);
    }
	
	//chdir(path);
    //ret = stat(absolutely_path, &st);
	ret = stat(ptr->d_name, &st);
	printf("stat return value = %d\n", ret);
	
	if (ret == 0) {
		printf("\t %s = %ld(byte)\n", ptr->d_name, st.st_size);
		printf("\t size ========%0.3lf KB  %0.3lf M   %0.3lf G ======\n",
		st.st_size/1024.0,st.st_size/1024.0/1024.0,st.st_size/1024.0/1024.0/1024.0);
	}

	#if 0
    printf("size = %f(kb) %s %s %s\n", (float)st.st_size/1000.0, 
		ctime(&st.st_ctime),  /* created  */
		ctime(&st.st_atime),  /* access   */
		ctime(&st.st_mtime)); /* modified */
	#endif
  }
  
  closedir(dir);
  
  return 1;
}

void test()
{
    struct stat buf;
	int ret = -1;

    ret = stat("/home/share/work/test-verification/dir/test", &buf);
	//ret = stat("/home/share/work/test-verification/dir/file-size.c", &buf);

	printf("stat result = %d\n", ret);
	if (ret == 0) {
		printf("\t size = %ld(byte)\n", buf.st_size);
		return ;
	}


    printf("file size = %s\n", "ERROR");
}

void main()
{
	char * path = "/home/share/work/test-verification/dir/test";

	read_file_list(path);
	//test();
}
